package org.jeecg.modules.rental.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.rental.entity.RentalAccount;
import org.jeecg.modules.rental.entity.RentalOrder;
import org.jeecg.modules.rental.mapper.RentalAccountMapper;
import org.jeecg.modules.rental.req.RentalEBikeOrderReq;
import org.jeecg.modules.rental.service.IRentalOrderService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: 租赁订单
 * @Author: sean
 * @Date: 2024-06-17
 * @Version: V1.0
 */
@Api(tags = "租车订单")
@RestController
@RequestMapping("/rental/order")
@RequiredArgsConstructor
@Slf4j
public class RentalOrderController extends JeecgController<RentalOrder, IRentalOrderService> {
    private final IRentalOrderService rentalOrderService;

    private final RentalAccountMapper rentalAccountMapper;

    private final RedisUtil redisUtil;

    /**
     * 分页列表查询
     *
     * @param rentalOrder
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "租车订单-分页列表查询")
    @ApiOperation(value = "租车订单-分页列表查询", notes = "租车订单-分页列表查询")
    @GetMapping(value = "/list")
    @PermissionData(pageComponent="rental/order/list")
    public Result<IPage<RentalOrder>> queryPageList(RentalOrder rentalOrder,
                                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                    HttpServletRequest req) {
        QueryWrapper<RentalOrder> queryWrapper = QueryGenerator.initQueryWrapper(rentalOrder, req.getParameterMap());
        Page<RentalOrder> page = new Page<RentalOrder>(pageNo, pageSize);
        IPage<RentalOrder> pageList = rentalOrderService.page(page, queryWrapper);

        if(ObjectUtil.isNotEmpty(pageList) && ObjectUtil.isNotEmpty(pageList.getRecords())){
            // 获取所有用户 ID
            List<String> accountIds = pageList.getRecords().stream().map(RentalOrder::getAccountId).distinct().collect(Collectors.toList());
            // 查询所有相关的用户信息
            List<RentalAccount> payAccountList = rentalAccountMapper.selectBatchIds(accountIds);
            // 遍历订单记录，填充用户姓名
            for (RentalOrder record : pageList.getRecords()) {
                // 查找对应的用户信息
                RentalAccount payAccount = payAccountList.stream()
                        .filter(pa -> pa.getId().equals(record.getAccountId()))
                        .findFirst()
                        .orElse(null);
                if (payAccount != null) {
                    record.setIdentityName(payAccount.getIdentityName()); // 设置用户姓名
                }
            }
        }
        return Result.OK(pageList);
    }

    @AutoLog(value = "租车订单-添加")
    @ApiOperation(value = "租车订单-添加", notes = "租车订单-添加")
    @PostMapping(value = "/add")
    public Result<RentalOrder> add(@RequestBody RentalOrder req) {
        rentalOrderService.save(req);
        return Result.OK("common.add.success");

    }

    /**
     * 编辑
     *
     * @param rentalOrder
     * @return
     */
    @AutoLog(value = "租车订单-编辑")
    @ApiOperation(value = "租车订单-编辑", notes = "租车订单-编辑")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody RentalOrder rentalOrder) {
        rentalOrderService.updateById(rentalOrder);
        return Result.OK("common.edit.success");
    }

    @AutoLog(value = "续租订单-添加")
    @ApiOperation(value = "续租订单-添加", notes = "租车订单-添加")
    @PostMapping(value = "/renewal")
    public Result<RentalOrder> renewal(@RequestBody RentalEBikeOrderReq req) {
        return rentalOrderService.renewal(req);
    }

    @AutoLog(value = "租车订单-客户创建支付订单")
    @ApiOperation(value = "租车订单-添加", notes = "租车订单-客户创建支付订单")
    @PostMapping(value = "/confirm")
    public Result<RentalOrder> confirm(@RequestBody RentalEBikeOrderReq req) {
        return rentalOrderService.confirmOrder(req);

    }

    @ApiOperation(value = "取消订单", notes = "取消订单")
    @GetMapping(value = "/cancellation")
    public Result<Boolean> cancellationOrder(@RequestParam(name = "orderId") String orderId) {
        return rentalOrderService.cancellationOrder(orderId);
    }



    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "租车订单-通过id删除")
    @ApiOperation(value = "租车订单-通过id删除", notes = "租车订单-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        rentalOrderService.removeById(id);
        return Result.OK("common.delete.success");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "租车订单-批量删除")
    @ApiOperation(value = "租车订单-批量删除", notes = "租车订单-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.rentalOrderService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("common.delete.batch.success");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "租车订单-通过id查询")
    @ApiOperation(value = "租车订单-通过id查询", notes = "租车订单-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<RentalOrder> queryById(@RequestParam(name = "id", required = true) String id) {
        RentalOrder rentalOrder = rentalOrderService.getById(id);
        if (rentalOrder == null) {
            return Result.error("common.query.not.found", null);
        }
        return Result.OK(rentalOrder);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param rentalOrder
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, RentalOrder rentalOrder) {
        return super.exportXls(request, rentalOrder, RentalOrder.class, "rental_order");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, RentalOrder.class);
    }


    /**
     * 分页列表查询
     *
     * @param rentalOrder
     * @return
     */
    //@AutoLog(value = "租车订单-分页列表查询")
    @ApiOperation(value = "租车订单-分页列表查询", notes = "租车订单-分页列表查询")
    @GetMapping(value = "/order-list")
    public Result<IPage<RentalOrder>> orderList(RentalOrder rentalOrder, Page page) {
        Page<RentalOrder> pageList = rentalOrderService.orderList(page, rentalOrder);
        return Result.OK(pageList);
    }


}
